﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Data.Base;

namespace XfTechOAWeb.EFCore.Base
{
    /// <summary>
    /// 工作单元的实现类
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        //数据库dbcontext上下文
        private readonly DbContext _dbContext;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="dbContext"></param>
        public UnitOfWork(DbContext dbContext)
        {
            _dbContext= dbContext;
        }

        /// <summary>
        /// 提交 事务（非异步的）
        /// </summary>
        /// <returns></returns>
        public int SaveChanges()
        {
            return _dbContext.SaveChanges();
        }

        /// <summary>
        /// 异步 提交  （await / async 异步编程）
        /// </summary>
        /// <returns></returns>
        public async Task<int> SaveChangesAsync()
        {
            int result;
            try
            {
                result = await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                //抛出异常
                //throw e;
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.Message);
            }

            return result;
        }
    }
}
